package com.lcredu.spring.component;

import com.lcredu.spring.annotation.Component;
import com.lcredu.spring.processe.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 黎长容
 * @date 2025-07-16 19:15
 */
@Component
public class LcrBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        //这里我可以进行判断,针对某一些类,直接面向切面!
        if (bean instanceof Car) {
            System.out.println("什么?你居然造了一台小汽车???");
        }
        System.out.println("后置处理器LcrBeanPostProcessor -- postProcessBeforeInitialization 被调用 " + beanName + " bean= " + bean.getClass());
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("后置处理器LcrBeanPostProcessor -- postProcessAfterInitialization 被调用 " + beanName + " bean= " + bean.getClass());
        //目标:判断是不是需要处理的类(smartDog),返回代理对象
        //如果是,就加入前置通知(这里默认切入点为getSum)
        //如果不是,就正常执行方法
        if ("smartDog".equals(beanName)) {
            Object objectProxy = Proxy.newProxyInstance(LcrBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            String methodName = method.getName();
                            Object result = null;
                            if ("getSum".equals(methodName)) {
                                //前置通知
                                SmartAnimalAspect.showBeginLog();
                                result = method.invoke(bean, args);
                                //后置通知
                                SmartAnimalAspect.showSuccessLog();
                            } else {
                                result = method.invoke(bean, args);
                            }
                            return result;
                        }
                    });
            return objectProxy;
        }
        //如果不需要aop,就返回原生对象
        return bean;
    }
}
